// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <cstdint>

#include <pollux/common/base/bit_util.h>

namespace kumo::pollux::common::hll {
    /// This method implements the Murmur3Hash128::hash64 methods to match Presto
    /// Java.
    class Murmur3Hash128 {
    public:
        /// This method implements
        /// https://github.com/airlift/slice/blob/44896889dcef7a16a2c14800a4a392934909c2cc/src/main/java/io/airlift/slice/Murmur3Hash128.java#L152.
        static int64_t hash64(const void *data, int32_t length, int64_t seed);

        /// This method implements
        /// https://github.com/airlift/slice/blob/44896889dcef7a16a2c14800a4a392934909c2cc/src/main/java/io/airlift/slice/Murmur3Hash128.java#L248.
        static int64_t hash64ForLong(int64_t data, int64_t seed) {
            uint64_t h2 = seed ^ sizeof(int64_t);
            uint64_t h1 = h2 + (h2 ^ (bits::rotateLeft64(data * C1, 31) * C2));
            return static_cast<int64_t>(mix64(h1) + mix64(h1 + h2));
        }

        static void
        hash(const void *key, const int32_t len, const uint32_t seed, void *out);

    private:
        static constexpr uint64_t C1 = 0x87c37b91114253d5L;
        static constexpr uint64_t C2 = 0x4cf5ad432745937fL;

        static uint64_t mix64(uint64_t k) {
            k ^= k >> 33;
            k *= 0xff51afd7ed558ccdL;
            k ^= k >> 33;
            k *= 0xc4ceb9fe1a85ec53L;
            k ^= k >> 33;

            return k;
        }
    };
} // namespace kumo::pollux::common::hll
